package service

import (
	"context"

	pb "Cosmos.Communication/api/v1"
	biz "Cosmos.Communication/internal/biz"
	"github.com/go-kratos/kratos/v2/log"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

type ProcessorRuntimeServiceService struct {
	pb.UnimplementedProcessorRuntimeServiceServer
	responbility Responsibility
	logHelper    *log.Helper
}

func NewProcessorRuntimeServiceService(responbility Responsibility, logger log.Logger) *ProcessorRuntimeServiceService {
	return &ProcessorRuntimeServiceService{responbility: responbility, logHelper: log.NewHelper(logger)}
}

func (s *ProcessorRuntimeServiceService) Invoke(ctx context.Context, req *pb.InvokeRequest) (result *pb.Result, err error) {
	result = &pb.Result{
		Code: 200,
	}

	if req == nil {
		result.Code = 400
		s.logHelper.Info("Invoke_Callback req is nil")
		return
	}

	s.logHelper.Info("Invoke_Processor param", req.Param, req.Type)

	var meta = &biz.Meta{}
	meta.Get(ctx)
	callReq := &biz.InvokeRequest{
		Invoker:    meta.Target,
		Function:   req.Type.GetValue(),
		Parameters: req.Param.GetValue(),
	}
	callResult, err := s.responbility.Invoke(ctx, callReq)
	if err != nil {
		result.Code = 500
		result.Message = &wrapperspb.StringValue{Value: err.Error()}
		return
	}
	if callResult == nil {
		result.Code = 500
		result.Message = &wrapperspb.StringValue{Value: "Invoke result is nil"}
		return
	}
	if callResult.Code != 200 {
		result.Code = int32(callResult.Code)
		result.Message = &wrapperspb.StringValue{Value: callResult.Message}
		return
	}

	response := &pb.InvokeResponse{
		Data: &wrapperspb.StringValue{Value: callResult.Data.Value},
	}
	if result.Data, err = anypb.New(response); err != nil {
		return
	}
	return
}
func (s *ProcessorRuntimeServiceService) Notify(ctx context.Context, req *pb.Notification) (result *pb.Result, err error) {
	result = &pb.Result{
		Code: 200,
	}

	if req == nil {
		result.Code = 400
		s.logHelper.Info("Notify_Processor req is nil")
		return
	}

	s.logHelper.Info("Notify_Processor param", req.Topic, req.Message, req.RoutingKey)

	var meta = &biz.Meta{}
	meta.Get(ctx)
	callReq := &biz.NotifyRequest{
		Topic:      req.Topic.GetValue(),
		RoutingKey: req.RoutingKey.GetValue(),
		Message:    req.Message.GetValue(),
	}
	go s.responbility.Notify(ctx, callReq)

	return
}
